import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import { Modal, notification } from 'ant-design-vue'
import { ACCESS_TOKEN, TENANT_ID,USER_NAME, USER_INFO, USER_AUTH } from '@/store/mutation-types'
import router from '@/router/index'

let apiBaseUrl = window._CONFIG['domianURL'] || "/jeecg-boot";
/**
 * 【指定 axios的 baseURL】
 * 如果手工指定 baseURL: '/jeecg-boot'
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
//0锁定，1未锁定，新增按钮专用，勿动
//新增按钮专用提交计时器，勿动
let addTimer=null

//console.log("apiBaseUrl= ",apiBaseUrl)
// 创建 axios 实例
const service = axios.create({
  //baseURL: '/jeecg-boot',
  baseURL: apiBaseUrl, // api base_url
  timeout: 90000 // 请求超时时间
})

const err = (error) => {
  let response=error.response
  if (response) {
    let that=this;
    let data = response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    console.log("------异常响应------",token)
    console.log("------异常响应------",response.status)
    switch (response.status) {
      case 403:
        notification.error({ message: '系统提示', description: '拒绝访问',duration: 4})
        clearRequest(response)
        break
      case 500:
        console.log("------response------",response)
        // update-begin- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
        let type=response.request.responseType;
        clearRequest(response)
        if(type === 'blob'){
          blobToJson(data);
          break;
        }

        if(data.message.includes('用户不存在')){
          Vue.prototype.$Jnotification.error({ message: '系统提示', description: '用户不存在!'})
          setTimeout(()=>{
            Vue.ls.remove(ACCESS_TOKEN)
            router.push('/user/login')
          },3000)
          return
        }
        
        // update-end- --- author:liusq ------ date:20200910 ---- for:处理Blob情况----
        //notification.error({ message: '系统提示', description:'Token失效，请重新登录!',duration: 4})
        if(token && data.message.includes("Token失效")){
          // update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              store.dispatch('Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                try {
                  let path = window.document.location.pathname
                  console.log("location pathname -> "+path)
                  if(path!="/" && path.indexOf('/user/login')==-1){
                    window.location.reload()
                  }
                }catch (e) {
                  window.location.reload()
                }
              })
            }
          })
          // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
        }
        break
      case 404:
          notification.error({ message: '系统提示', description:'很抱歉，资源未找到!',duration: 4})
        clearRequest(response)
        break
      case 504:
        notification.error({ message: '系统提示', description: '网络超时'})
        clearRequest(response)
        break
      case 401:
        Vue.ls.remove(ACCESS_TOKEN)
        router.push('/user/login')
        // notification.error({ message: '系统提示', description:'未授权，请重新登录',duration: 4})
        // if (token) {
        //   store.dispatch('Logout').then(() => {
        //     setTimeout(() => {
        //       window.location.reload()
        //     }, 1500)
        //   })
        // }
        clearRequest(response)
        break
      default:
        clearRequest(response)
        notification.error({
          message: '系统提示',
          description: data.message,
          duration: 4
        })
        break
    }
  }
  return Promise.reject(error)
};
let urlPending=[]
let lockTimeInMills=2000
var CancelToken= axios.CancelToken
let removePeding=(config)=>{
  if (config) {
    for (let i in urlPending) {
      if (urlPending[i].url === apiBaseUrl + config.url) {
        urlPending[i].f()
        console.log(urlPending[i].url)
        notification.error({ message: '系统提示', description:'请不要重复添加!',duration: 4})
        addTimer=window.setTimeout(() => {
          urlPending.splice(i, 1);
        }, lockTimeInMills)
        config.cancelToken=source.token
        source.cancel("操作被用户取消");
      }
    }
  }
}
var source=CancelToken.source()
// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)

  config.headers[ 'client-id' ] = 'web'
  config.headers[ 'user-id' ] = Vue.ls.get('user_id') || ''
  // if (config.url.includes('/api/erpmng/')) {
  //   console.log('执行替换system')
  //   config.url = config.url.replace('/api/erpmng/', '/jeecg-system-erp-wc/api/erpmng/')
  // }
  // console.log('indexOfErp url:' + config.url.includes('/api/erp/'))
  // if (config.url.includes('/api/erp/')) {
  //   console.log('执行替换erp')
  //   config.url = config.url.replace('/api/erp/', '/jeecg-erp-wc/api/erp/')
  // }

  if (token) {
    config.headers['Authorization'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  //update-begin-author:taoyan date:2020707 for:多租户
  let tenantid = Vue.ls.get(TENANT_ID)
  if (!tenantid) {
    tenantid = 0;
  }
  config.headers['tenant_id'] = tenantid
  //update-end-author:taoyan date:2020707 for:多租户
  if(config.method=='get'){
    if(config.url){
      if (config.url.indexOf("api/erpmng/sys/dict/getDictItems") < 0) {
        config.params = {
          _t: Date.parse(new Date()) / 1000,
          ...config.params
        }
      }
    }else{
      return
    }
    
  }else if(config.method=='post'){
    if (config.url.endsWith("/add")) {  //   console.log('执行替换system')
      //post，add请求，加锁，收到响应时解除锁定,5秒内未收到响应，到第5秒时也会自动解除锁定
      // removePeding(config) // 取消锁
      config.CancelToken = new CancelToken(function (c) {
        // 做下判断防止请求加锁去除不掉
        if (urlPending &&urlPending.length) {
          urlPending.map((value, index) => {
            if (value.url != (apiBaseUrl + config.url)) {
              urlPending.push({
                url: apiBaseUrl + config.url,
                f: c
              })
            }
          })
        } else {
          urlPending.push({
            url: apiBaseUrl + config.url,
            f: c
          })
        }
      })
      /*if(lock==1){
        console.log("重复请求了")
        notification.error({ message: '系统提示', description:'请不要重复添加!',duration: 4})
        addTimer = window.setTimeout(() => {
          lock=0
        }, lockTimeInMills)
        config.cancelToken=source.token
        source.cancel("操作被用户取消");
      }else{
        lock=1
      }*/
    }
  }
  // 由于换了新缓存的字段，导致获取不到用户信息，想做一个无痕的数据刷新
  // 先判断用户数据是否为空
  // 判断USER_INFO为Login_Userinfo_erp 且 Login_Userinfo_erp为空，且Login_Userinfo有值
  if (USER_INFO == 'Login_Userinfo_erp' && !Vue.ls.get(USER_INFO) && Vue.ls.get('Login_Userinfo')) {
    Vue.ls.set(USER_INFO, Vue.ls.get('Login_Userinfo'), 7 * 24 * 60 * 60 * 1000)
    Vue.ls.set(USER_NAME, Vue.ls.get('Login_Username'), 7 * 24 * 60 * 60 * 1000)
    Vue.ls.set(USER_AUTH, Vue.ls.get('LOGIN_USER_BUTTON_AUTH'), 7 * 24 * 60 * 60 * 1000)
  }
  return config
},(error) => {
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use((response) => {

    if(response.data.code==1005){
      Vue.ls.remove(ACCESS_TOKEN)
      Vue.prototype.$Jnotification.error({message: '系统提示', description: response.data.msg})
      window.location.reload()
    }
    clearRequest(response)
    return response.data
  }, err)

const installer = {
  vm: {},
  install (Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}
function clearRequest(data){

  for (let i in urlPending) {
    if (urlPending[i].url ===  data.config.url) {
      urlPending.splice(i, 1);
    }
  }
  if(addTimer){
    window.clearTimeout(addTimer)
    addTimer=null
  }
}
/**
 * Blob解析
 * @param data
 */
function blobToJson(data) {
  let fileReader = new FileReader();
  let token = Vue.ls.get(ACCESS_TOKEN);
  fileReader.onload = function() {
    try {
      let jsonData = JSON.parse(this.result);  // 说明是普通对象数据，后台转换失败
      console.log("jsonData",jsonData)
      if (jsonData.status === 500) {
        console.log("token----------》",token)
        if(token && jsonData.message.includes("Token失效")){
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              store.dispatch('Logout').then(() => {
                Vue.ls.remove(ACCESS_TOKEN)
                window.location.reload()
              })
            }
          })
        }
      }
    } catch (err) {
      // 解析成对象失败，说明是正常的文件流
      console.log("blob解析fileReader返回err",err)
    }
  };
  fileReader.readAsText(data)
}

export {
  installer as VueAxios,
  service as axios
}